/**
 * @file      gateway_manager.c
 * @brief
 * @version   1.0
 * @date      2023.12.14
 *
 * @copyright Copyright (c) 2018 UCchip Technology Co.,Ltd. All rights reserved.
 *
 * Change Logs:
 * Date          Author       Notes
 * 2023.12.14    ucchip       the first version
 *
 */

#include "gateway_manager.h"
#include "auth_manager.h"
#include "config_api.h"
#include "downlink_manager.h"
#include "manager_queue.h"
#include "module_queue_struct.h"
#include "uplink_manager.h"
#include "watchdog_app.h"
#include <rtthread.h>

#define DBG_ENABLE
#define DBG_SECTION_NAME "gw_mn"
#include "uc_log.h"

// 网关管理线程任务队列句柄
static void *manager_queue_handle = NULL;

/**
 * @brief 创建网关管理线程任务队列
 *
 * @return int 0表示成功，非0表示失败
 */
int gateway_manager_create_queue(void)
{
    // create wiota app manager queue.
    manager_queue_handle = manager_create_queue("app_manager", 4, 100, UC_SYSTEM_IPC_FLAG_PRIO);
    if (manager_queue_handle == RT_NULL)
    {
        TRACE_E("manager_create_queue error\n");
        return 1;
    }

    return 0;
}

/**
 * @brief 获取网关管理线程任务队列
 *
 * @return void* 网关管理线程任务队列句柄
 */
void *get_gateway_manager_queue(void)
{
    return manager_queue_handle;
}

/**
 * @brief 处理来自自身线程的命令
 *
 * @param cmd  自身线程需要串行执行的命令
 * @param data 数据
 */
void manager_handle_self_msg(int cmd, void *data)
{
    switch (cmd)
    {
    case GATEWAY_REBOOT:
        TRACE_E("gateway will restart!!!\n");
        // 延迟200ms，保证某些发送任务完成
        rt_thread_mdelay(200);
        watchdog_reboot();
        break;

    default:
        break;
    }
}

/**
 * @brief 网关管理线程处理主函数，处理来自WIoTa的上行消息、来自net、web、serial、serial debug或BT的下行消息或来自自身的串行消息
 *
 * @param para 创建线程时传入的参数
 */
void gateway_manager_task(void *para)
{
    module_queue_message_t *page;

    TRACE_D("gateway_manager_task begin\n");

    if (UC_TRANSMISSION_MODE != uc_static_get_gateway_auth_cfg()->work_mode)
    {
        manager_init_auth();
    }

    while (1)
    {
        if (QUEUE_EOK != manager_recv_queue(manager_queue_handle, (void *)&page, UC_QUEUE_WAITING_FOREVER))
        {
            continue;
        }

        switch (page->src_task)
        {
        case GATEWAY_MANAGER_MODULE:
            manager_handle_self_msg(page->cmd, (void *)page->data);
            break;

        case WIOTA_APP_MODULE:
            manager_handle_uplink_msg(page->cmd, (void *)page->data);
            break;

        case NET_APP_MODULE:
        case SERIAL_MANAGER_MODLE:
        case SERIAL_DEBUG_MANAGER_MODULE:
        case SERIAL_485_MANAGER_MODULE:
        case SERIAL_UART_MANAGER_MODULE:
        case BT_MANAGER_MODULE:
        case AUDIO_APP_MODULE:
            manager_handle_downlink_msg(page->src_task, page->cmd, (void *)page->data);
            break;

        default:
            break;
        }

        if (RT_NULL != page)
        {
            rt_free(page);
            page = RT_NULL;
        }
    }
}